// commands.js

var AppalachianCommands = {};

AppalachianCommands.showWelcome = function() {
    window.open("chrome://appalachian/content/welcome.xul", "appalachian-welcome", "chrome=yes,modal=yes,resizable=yes,width=400,height=400");
}

AppalachianCommands.showIdManager = function() {
    window.open("chrome://appalachian/content/id-manager.xul", "appalachian-id-manager", "chrome=yes,modal=yes,resizable=yes,width=600,height=400");
};

AppalachianCommands.showPreferences = function() {
    window.open("chrome://appalachian/content/preferences.xul", "appalachian-preferences", "chrome=yes,modal=yes,resizable=yes,width=300,height=300");
};

AppalachianCommands.useID = function(id, field, formRef) {
    AppalachianDebug.trace("commands.js", "> useID " + id + ", " + field + ", " + formRef);
    // fill in and submit when id is selected
    if (field == null) field = 'openid_url';
    var stringBundle = document.getElementById("appalachian-bundle");
    var inputs = [];
    if (formRef == null) {
        inputs = content.document.getElementsByName(field);
    } else {
        inputs.push(content.document.forms[formRef].wrappedJSObject.elements[field]);
    }

    if (inputs.length == 1) {
        inputs[0].value = AppalachianDB.getInfo(id).getURL();
        if (!formRef) {
            var formParent = inputs[0].form;
            for (var j = 0; j < content.document.forms.length; j++) {
                if (content.document.forms[j] == formParent) {
                    formRef = j;
                    break;
                }
            }
        }
        if (isNaN(Number(field))) {
            var formparts = content.document.forms[formRef].elements;
            for (var j = 0; j < formparts.length; j++) {
                if (formparts[j] == inputs[0]) {
                    field = j;
                    break;
                }
            }
        }
        Appalachian.getState().storeUse(id, content.document.location.href, field, formRef, inputs[0].form.method, inputs[0].form.action);
        Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
        inputs[0].form.submit();
    } else if (inputs.length != 1) {
        if (content.document.forms.length > 0) {
            var focused = document.commandDispatcher.focusedElement;
            if (!focused) {
                var fieldmsg = stringBundle.getString("clickfield");
                alert(fieldmsg);
                return;
            }
            if (focused.type != 'text') {
                var fieldmsg = stringBundle.getString("nontextfield");
                alert(fieldmsg);
                return;
            }
            focused.blur();
            focused.value = AppalachianDB.getInfo(id).getURL();
            var formParent = focused.form;
            for (var j = 0; j < content.document.forms.length; j++) {
                if (content.document.forms[j] == formParent) {
                    formRef = j;
                    break;
                }
            }
            Appalachian.getState().storeUse(id, content.document.location.href, focused.name, formRef, focused.form.method, focused.form.action);
            Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
            focused.form.submit();
        } else {
            return;
        }
    }

};

AppalachianCommands.automateAction = function() {
    // has the plug-in been initialized?  open up the manager if not
    var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    var init = prefs.getBoolPref("extensions.appalachian.initialized");
    var defaultID = prefs.getIntPref("extensions.appalachian.defaultID");
    var defaults = prefs.getBoolPref("extensions.appalachian.useDefault");
    // @@@ init here?
    if (!init) {
        AppalachianCommands.showWelcome();
        return;
    }

    // if openid.server is a link rel, pop up add box with url as id
    AppalachianDebug.trace("commands.js", "automateAction linkrel");
    var links = content.document.getElementsByTagName('link');
    for (var i = 0; i < links.length; i++) {
        if (links[i].hasAttribute("rel") && links[i].getAttribute("rel").indexOf("openid.server") != -1) {
            if(!AppalachianDB.exists(content.document.location.href)) {
                Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
                window.openDialog("chrome://appalachian/content/add-openid.xul", "appalachian-add-openid", "chrome,modal", { url : content.document.location.href , server : [links[i].getAttribute("href")].toSource(), saved : function() { Appalachian.getState().advance(APPALACHIAN_ACTION_SAVE) }, cancelled: function() { Appalachian.getState().advance(APPALACHIAN_ACTION_ABORT) } } );
                return;
            } else {
                var stringBundle = document.getElementById("appalachian-bundle");
                var alreadymsg = stringBundle.getString("alreadyexists");
                alert(alreadymsg);
            }
        }
    }

    // try doing a yadis thing
    AppalachianDebug.trace("commands.js", "automateAction yadis");
    if (Appalachian.getState().getCurrentState() == "addavailable") {
        var ylib = new Yadis(content.document.location.href);
        Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
        var cont = function(answer) {
            window.openDialog("chrome://appalachian/content/add-openid.xul", "appalachian-add-openid", "chrome,modal", { url : content.document.location.href , server : answer.toSource(), saved : function() { Appalachian.getState().advance(APPALACHIAN_ACTION_SAVE) }, cancelled: function() { Appalachian.getState().advance(APPALACHIAN_ACTION_ABORT) } } );        
        };
        ylib.getAuthorities(cont, content.document);
        return;
    }

    var loc = content.document.location.href;
    var ids = AppalachianDB.listUsesIds(loc);
    if (ids.length == 1) {
        // if requestor is familiar, only one id associated,
        // fill in and submit
        AppalachianDebug.trace("commands.js", "automateAction useID");
        AppalachianCommands.useID(ids[0].openid, ids[0].field, ids[0].form);
    } else if (ids.length > 1) {
        // if requestor is familiar and several ids,
        // popup id selection menu; submit on selection
        var openids = new Array();
        for (var k = 0; k < ids.length; k++) {
            openids.push(AppalachianDB.getInfo(ids[k].openid));
        }
        AppalachianCommands.addIDs("appalachian-status-id-selection-menu", openids, true);
        var menu = document.getElementById("appalachian-status-id-selection-menu");
        menu.showPopup(document.getElementById("appalachian-status-icon"), -1, -1, "popup");
    } else if (ids.length == 0 && defaults && defaultID > 0 ) {
        // if requestor is unknown, fill in default
        AppalachianCommands.useID(defaultID, null, null);
    } else if (ids.length == 0 && !defaults) {
        AppalachianCommands.addIDs("appalachian-status-id-selection-menu", null, true);
        var menu = document.getElementById("appalachian-status-id-selection-menu");
        menu.showPopup(document.getElementById("appalachian-status-icon"), -1, -1, "popup");        
    } else {
        AppalachianCommands.showWelcome();
        return;
    }
};

AppalachianCommands.addIDs = function(menu, ids, explain) {
    var m = document.getElementById(menu);
    for (var i = m.childNodes.length; i > 0; i--) {
        var n = m.childNodes[i-1];
        if (n.id && n.id.indexOf(menu + "-openid-") == 0)
            m.removeChild(n);
    }

    var marker = m.firstChild;
    if (!ids) ids = AppalachianDB.listAll();
    var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    var defaultid = prefs.getIntPref("extensions.appalachian.defaultID");
    var defaults = prefs.getBoolPref("extensions.appalachian.useDefault");
    if (ids.length == 0) {
        AppalachianCommands.showIdManager();
        return;
    }
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var item = document.createElement("menuitem");
        var label = id.getUse();
        if (defaults)
            label += (id.getID() == defaultid) ? " (default)" : "";
        var use;
        var useID;
        if (AppalachianDB.useExists(id.getID(), content.document.location.href)) {
            useID = AppalachianDB.getUseId(id.getID(), content.document.location.href);
        }
        if (useID) use = AppalachianDB.getUse(useID, id.getID());
        item.setAttribute("id", menu + "-openid-" + id.getID());
        item.setAttribute("label", label);
        if (use) {
            item.setAttribute("oncommand", "AppalachianCommands.useID(" + id.getID() + "," + use.field + "," + use.form + ");");
        } else {
            item.setAttribute("oncommand", "AppalachianCommands.useID(" + id.getID() + ",null,null);");
        }
        m.insertBefore(item, marker);
    }
    if (explain) {
        var exp = document.createElement("menuitem");
        var explabel = "Choose your OpenID";
        exp.setAttribute("id", menu + "-openid-explain");
        exp.setAttribute("label", explabel);
        exp.setAttribute("disabled", true);
        m.insertBefore(exp, m.firstChild);
    }
};

// continuation for API use
AppalachianCommands.apiLogin = false;
